package com.warrantyhotel.android.ui;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;

import com.warrantyhotel.android.R;
import com.warrantyhotel.android.adapter.AccounIdentifyAdapter;
import com.warrantyhotel.android.db.QueriesCodes;
import com.warrantyhotel.android.model.AccountIdentifyObject;
import com.warrantyhotel.android.model.AccountIdentifySaveObject;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.service.UpdateIntentService;
import com.warrantyhotel.android.util.DetachableResultReceiver;
import com.warrantyhotel.android.util.DetachableResultReceiver.Receiver;
import com.warrantyhotel.android.util.ToastUtil;

@SuppressLint("NewApi")
public class ChanageEmailActivity extends Activity implements Receiver, OnClickListener, OnItemClickListener, OnCreateContextMenuListener {

	private ListView listView;
	private DetachableResultReceiver receiver;
	private ProgressDialog progress;
	private LayoutInflater mInflater;
	private AccountIdentifyObject[] result = null;
	private static final int ADD_NEW_DIALOG = 1;
	private String[] arrayAction;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.change_email);

		mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		listView = (ListView) findViewById(R.id.account_list);
		listView.setOnItemClickListener(this);

		View view = mInflater.inflate(R.layout.list_footer_account, null);
		listView.addFooterView(view);
		view.setOnClickListener(this);

		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(this);
		fetchList();

		progress = ProgressDialog.show(this, getString(R.string.loading), getString(R.string.please_wait), true, false);

	}

	private void showDialogList(final int position) {
		final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		View view = mInflater.inflate(R.layout.list_action, null);
		ListView listView = (ListView) view.findViewById(R.id.list);

		arrayAction = new String[] { getString(R.string.delete_user), getString(R.string.edit_user) };
		if (result[position].isContact()) {
			arrayAction = new String[] { getString(R.string.delete_user), getString(R.string.edit_user) };
		} else {
			arrayAction = new String[] { getString(R.string.edit_user) };
		}
		listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayAction));
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int positionInner, long id) {
				if (getString(R.string.delete_user).equals(arrayAction[positionInner])) {
					removeUser(result[position].getAccountIdentityID());
					alertDialog.dismiss();
				} else if (getString(R.string.edit_user).equals(arrayAction[positionInner])) {
					removeDialog(ADD_NEW_DIALOG);
					Bundle bundle = new Bundle();
					bundle.putString(Keys._name, result[position].getValue());
					bundle.putString(Keys._account_identity_by_id, result[position].getAccountIdentityID());
					bundle.putString(Keys._account_identity_type, result[position].getAccountIdentityTypeID());
					showDialog(ADD_NEW_DIALOG, bundle);
					alertDialog.dismiss();
				}
			}
		});

		alertDialog.setView(view);
		alertDialog.show();
	}

	private void removeUser(String id) {
		Intent removeIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateIntentService.class);
		removeIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
		removeIntent.putExtra(Keys._account_identity_by_id, id);
		removeIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.ACCOUNT_IDENTITY_DELETE_BY_ID);
		startService(removeIntent);
	}

	private void fetchList() {
		Intent fetchIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateIntentService.class);
		fetchIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
		fetchIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.ACCOUNT_IDENTITY_BY_ACCOUNT_ID);
		startService(fetchIntent);
	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		switch (resultCode) {
		case UpdateIntentService.STATUS_RUNNING:
			break;
		case UpdateIntentService.STATUS_ERROR:
			if (progress != null)
				progress.dismiss();
			// ToastUtil.showText(getApplicationContext(),
			// resultData.getString(UpdateIntentService.ERROR_MESSAGE));
			break;
		case UpdateIntentService.STATUS_FINISHED:
			if (progress != null)
				progress.dismiss();

			if (resultData.containsKey(Keys._accountIdentify)) {
				result = (AccountIdentifyObject[]) resultData.getParcelableArray(Keys._accountIdentify);
				AccounIdentifyAdapter adapter = new AccounIdentifyAdapter(getApplicationContext(), 0, result);
				listView.setAdapter(adapter);
			} else if (resultData.containsKey(Keys._accountIdentify_save)) {
				ToastUtil.showText(ChanageEmailActivity.this, ((AccountIdentifySaveObject) resultData.getParcelable(Keys._accountIdentify_save)).getMessage());
				fetchList();
			} else if (resultData.containsKey(Keys._accountIdentify_delete)) {
				fetchList();
			}

			break;
		}
	}

	@Override
	public void onClick(View v) {
		removeDialog(ADD_NEW_DIALOG);
		showDialog(ADD_NEW_DIALOG);

	}

	private void linkNewUser(String name, String identy_id, String type) {
		Intent addIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateIntentService.class);
		addIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
		addIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.ADD_ACCOUNT_IDENTITY);
		addIntent.putExtra(Keys._email, name);
		addIntent.putExtra(Keys._account_identity_type, type);
		addIntent.putExtra(Keys._account_identity_by_id, identy_id);
		startService(addIntent);
	}

	@Override
	protected Dialog onCreateDialog(int id, final Bundle bundle) {

		switch (id) {
		case ADD_NEW_DIALOG:

			LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View layout = mInflater.inflate(R.layout.add_new_user, null);
			final EditText userEmail = (EditText) layout.findViewById(R.id.add_new_user);
			final Spinner spinner = (Spinner) layout.findViewById(R.id.spinner_mail_user);

			final String[] items = new String[] { getString(R.string.mail), getString(R.string.user) };
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(ChanageEmailActivity.this, android.R.layout.simple_spinner_item, items);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinner.setAdapter(adapter);

			if (bundle != null && bundle.containsKey(Keys._account_identity_type)) {
				String type = bundle.getString(Keys._account_identity_type);
				int position = 0;
				for (int i = 0; i < items.length; i++) {
					if (type.equals(items[i])) {
						position = i;
						break;
					}
				}
				spinner.setSelection(position);
				spinner.setEnabled(false);
			}

			if (bundle != null && bundle.containsKey(Keys._name))
				userEmail.setText(bundle.getString(Keys._name));

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(getString(R.string.enter_new_user_email));
			builder.setView(layout);
			builder.setIcon(getResources().getDrawable(R.drawable.icon_warranty));
			builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {

					String type = spinner.getSelectedItem().toString();

					if (type.equals(items[0])) {
						if (isEmailValid(userEmail.getText().toString())) {
							String identy_id = null;
							if (bundle != null && bundle.containsKey(Keys._account_identity_by_id)) {
								identy_id = bundle.getString(Keys._account_identity_by_id);
							}
							linkNewUser(userEmail.getText().toString(), identy_id, type);
						} else {
							ToastUtil.showText(ChanageEmailActivity.this, getString(R.string.incorrect_email));
						}
					} else if (type.equals(items[1])) {
						String identy_id = null;
						if (bundle != null && bundle.containsKey(Keys._account_identity_by_id)) {
							identy_id = bundle.getString(Keys._account_identity_by_id);
						}
						linkNewUser(userEmail.getText().toString(), identy_id, type);
					}
				}
			});
			builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

				}
			});
			return builder.create();

		}

		return super.onCreateDialog(id);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
		showDialogList(position);
		// if (result != null) {
		// Intent intent = new Intent();
		// intent.putExtra(Keys._accountId, result[position].getAccountID());
		// setResult(RESULT_OK, intent);
		// finish();
		// }

	}

	private boolean isEmailValid(String email) {
		boolean result = false;

		if (email != null) {
			Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+");
			Matcher matcher = pattern.matcher(email);
			result = matcher.matches();
		}
		return result;
	}

}
